package pulpfizz.pulp.body;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;

import org.jbox2d.collision.CircleShape;
import org.jbox2d.collision.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;

/**
 * A BodyDrawer implementation which simply draws a solid line and colored
 * stroke for each Shape contained within the body.
 * 
 * @author Greg
 * 
 */
public class SimpleBodyDrawer implements BodyDrawer
{
	private Color strokeColor = Color.black;
	private Color fillColor = Color.white;
	private Color circleMarkColor = Color.black;
	
	public void setStrokeColor(Color newStroke) {
		strokeColor = newStroke;
	}
	
	public void setFillColor(Color newFill) {
		fillColor = newFill;
	}
	
	public void setCircleMarkColor(Color newColor) {
		circleMarkColor = newColor;
	}
	
	public Color getStrokeColor() {
		return strokeColor;
	}
	
	public Color getFillColor() {
		return fillColor;
	}
	
	public Color getCircleMarkColor() {
		return circleMarkColor;
	}

	public void drawBody(PhysicsLayer physics, Body b, Graphics2D g2)
	{
		// We need to scale up the coordinates in order to use the integer Graphics2D draw methods.
		float coordScale = 1000;
		g2.scale(1 / coordScale, 1 / coordScale);

		float stroke = coordScale / physics.scaling;
		g2.setStroke(new BasicStroke(stroke));

		org.jbox2d.collision.Shape s = b.getShapeList();
		while (s != null)
		{
			switch (s.getType())
			{
				case CIRCLE_SHAPE:
					CircleShape c = (CircleShape) s;
					int rad = (int) (c.m_radius * coordScale);
					int x = (int) (c.getLocalPosition().x * coordScale); // Need to extract the localPosition from the circle shape.
					int y = (int) (c.getLocalPosition().y * coordScale);
					g2.setPaint(fillColor);
					g2.fillOval(x - rad, y - rad, rad * 2, rad * 2);
					g2.setPaint(strokeColor);
					g2.drawOval(x - rad + (int) stroke / 2, y - rad + (int) stroke / 2, rad * 2 - (int) stroke, rad * 2
							- (int) stroke);
					g2.setPaint(circleMarkColor);
					g2.drawLine(0, 0, 0, rad);
					break;

				case POLYGON_SHAPE:
					PolygonShape p = (PolygonShape) s;
					Vec2[] vertices = p.getVertices();
					int vertexCount = p.getVertexCount();
					int[] vertX = new int[vertexCount];
					int[] vertY = new int[vertexCount];
					for (int i = 0; i < vertexCount; i++)
					{
						vertX[i] = (int) (vertices[i].x * coordScale);
						vertY[i] = (int) (vertices[i].y * coordScale);
					}
					g2.setColor(fillColor);
					g2.fillPolygon(vertX, vertY, vertexCount);
					g2.setColor(strokeColor);
					g2.drawPolygon(vertX, vertY, vertexCount);
					break;
			}
			s = s.getNext();
		}
	}

	public boolean needsRedraw()
	{
		return false;
	}

}
